package com.park.web.controller.pub;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.park.client.model.pub.SensitiveWordModel;
import com.park.client.model.resource.ResourceCollectionModel;
import com.park.client.model.resource.ResourceCommentModel;
import com.park.client.model.resource.ResourceDownloadRecordModel;
import com.park.client.model.resource.ResourceFileModel;
import com.park.client.model.user.IntegralConsumeModel;
import com.park.client.model.user.UserModel;
import com.park.client.service.pub.SensitiveWordService;
import com.park.client.service.resource.ResouceFileService;
import com.park.client.service.resource.ResourceCollectionService;
import com.park.client.service.resource.ResourceCommentService;
import com.park.client.service.resource.ResourceDownloadRecordService;
import com.park.client.service.user.IntegralConsumeService;
import com.park.client.service.user.UserService;
import com.park.common.empty.EmptyUtils;
import com.park.common.file.FileUtil;
import com.park.common.util.PageData;
import com.park.common.util.Result;
import com.park.web.contant.Global;
import com.park.web.controller.BaseController;
import com.park.web.util.SessionUtil;

@Controller
@RequestMapping("/public/resource")
public class PublicResourceController extends BaseController{

	@Autowired
	private ResouceFileService resouceFileService;
	@Autowired
	private ResourceDownloadRecordService downloadRecordService;
	@Autowired
	private ResourceCollectionService resourceCollectionService;
	@Autowired
	private UserService userService;
	@Autowired
	private IntegralConsumeService consumeService;
	@Autowired
	private SensitiveWordService sensitiveWordService;
	@Autowired
	private ResourceCommentService resourceCommentService;
	
	/**
	 *单个下载详情 
	 */
	@RequestMapping("detail/{id}")
	public String detail(@PathVariable("id")Long id,HttpServletRequest request){
		//单个资源文件详情
		ResourceFileModel  rf = resouceFileService.selectByPrimaryKey(id);
		request.setAttribute("rf", rf);
		//根据标题查询相似资源
		ResourceFileModel fileModel = new ResourceFileModel();
		fileModel.setResourceType(rf.getResourceType());
		fileModel.setId(id);
		fileModel.setResourceTitle(rf.getResourceTitle());
		List<ResourceFileModel> rfsList =  resouceFileService.selectByTitle(fileModel);
		request.setAttribute("rfsList", rfsList);
		//资源评论
		ResourceCommentModel comment = new ResourceCommentModel();
		comment.setResourceId(id);
		PageData<ResourceCommentModel> commentList = this.resourceCommentService.commentList(comment);
		request.setAttribute("commentList", commentList.getRows());
		return Global.PUBLIC_PATH+"resource/resourceDetail";
	}
	
	/**
	 * 查询下载该资源需要的积分
	 */
	@RequestMapping("/getResourceScore")
	@ResponseBody
	public Result<Boolean> getResourceScore(@RequestParam("resourceId") Long resourceId,HttpSession session){
		Result<Boolean> result = new Result<>(true);
		UserModel user = SessionUtil.getSessionUser();
		ResourceFileModel rf = resouceFileService.selectByPrimaryKey(resourceId);
		ResourceDownloadRecordModel record = new ResourceDownloadRecordModel();
		record.setCreater(user.getId());
		record.setResourceId(resourceId);
		ResourceDownloadRecordModel r = downloadRecordService.selectByObject(record);
		if(r != null){
			result.setSuccess(false);
			result.setMessage("你已经下载过该资源，重复下载将不再扣积分!");
			return result;
		}
		
		if((user.getIntegral()-rf.getScore()) <0){
			result.setSuccess(false);
			result.setMessage("对不起,你的积分不够,请获取积分后在下载!");
//			result.setObject(user.getIntegral());
		}else{
			String path = rf.getFilePath();
			if(EmptyUtils.isEmpty(path)){
				result.setSuccess(false);
				result.setMessage("对不起,该文件已经不存在了!");
			}
		}
		return result;
	}
	
	/**
	 *单个资源下载
	 */
	@RequestMapping("downloadResource/{resourceId}")
	public String downloadResource(@PathVariable("resourceId") Long resourceId,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		UserModel user = SessionUtil.getSessionUser(session);
			ResourceFileModel rf = resouceFileService.selectByPrimaryKey(resourceId);
			response.setCharacterEncoding("utf-8");
			response.setContentType("multipart/form-data");
				//设置输出长度
		        response.setHeader("Content-Length", rf.getResourceSize()); 
		        String fileName =rf.getResourceTitle()+"."+rf.getFileType();
		        response.reset();//清除response中的缓存信息
				try {
					response.setHeader("Content-Disposition", "attachment;fileName="+new String(fileName.getBytes("utf-8"),"iso-8859-1"));
					FileUtil.getBytes(rf.getFilePath());
					//统计下载次数
					int downloadCount = rf.getDownloadCount();
					rf.setDownloadCount(downloadCount+1);
					resouceFileService.updateByPrimaryKeySelective(rf);
					ResourceDownloadRecordModel record = new ResourceDownloadRecordModel();
					record.setCreater(user.getId());
					record.setResourceId(resourceId);
					ResourceDownloadRecordModel r = downloadRecordService.selectByObject(record);
					if(r == null){
						//下载的时候扣除积分,已经下载过的不重复扣
						int jifen = user.getIntegral();
						user.setIntegral(jifen-rf.getScore());
						userService.updateByPrimaryKeySelective(user);
						//记录下载的资源
						downloadRecordService.insertSelective(record);
						//消费记录
						IntegralConsumeModel consume = new IntegralConsumeModel();
						consume.setCategory(0);
						consume.setCreateDate(new Date());
						consume.setReason("下载");
						consume.setUserId(user.getId());
						consume.setResourceId(resourceId);
						consume.setIntegral(rf.getScore());
						consumeService.insertSelective(consume);
					}
				} catch (Exception e) {
					logger.error("下载资源异常",e);
				}
		return null;
	}
	
	/**
	 * 资源收藏
	 */
	@RequestMapping("/collectionResource")
	@ResponseBody
	public Result<Boolean> collectionResource(@RequestParam("resourceId") Long resourceId,HttpSession session){
		Result<Boolean> result = new Result<>();
		ResourceCollectionModel record = new ResourceCollectionModel();
		record.setUserId(SessionUtil.getUserID());
		record.setResourceId(resourceId);
		ResourceCollectionModel r = resourceCollectionService.selectByObject(record);
		if(r != null){
			result.setSuccess(false);
			result.setMessage("你已收藏过，请勿重复收藏!");
		}else{
			record.setCollectionDate(new Date());
			boolean success =	resourceCollectionService.insertSelective(record);
			if(success){
				result.setSuccess(true);
				result.setMessage("恭喜你,收藏成功!");
			}else{
				result.setSuccess(false);
				result.setMessage("很遗憾,收藏失败!");
			}
		}
		return result;
	}
	
	/**
	 * 资源评论
	 */
	@RequestMapping("comment")
	@ResponseBody
	public Result<ResourceCommentModel> comment(ResourceCommentModel comment,HttpServletRequest request){
		Result<ResourceCommentModel> result = new Result<>();
		comment.setCreater(SessionUtil.getUserID());
		ResourceCommentModel c = resourceCommentService.selectIsExist(comment);
		if(c != null){
			result.setSuccess(false);
			result.setMessage("你已评论过，请勿重复评论");
		}else{
			//过滤敏感词
			String commentContent = comment.getCommentContent();
			List<SensitiveWordModel> words = sensitiveWordService.selectAll();
			for (SensitiveWordModel word : words) {
				commentContent = commentContent.replaceAll(word.getWord(), "***");
			}
			comment.setCommentContent(commentContent);
			comment.setCommentDate(new Date());
			comment.setCreater(SessionUtil.getUserID());
			boolean success = resourceCommentService.insertSelective(comment);
			if(success){
				result.setSuccess(success);
				result.setObj(comment);
				result.setMessage("评论成功");
				//评论成功，修改平均评分
				Integer avgScore = resourceCommentService.selectAvgScore(comment.getResourceId());
				ResourceFileModel record = resouceFileService.selectByPrimaryKey(comment.getResourceId());
				record.setCommentScore(avgScore);
				resouceFileService.updateByPrimaryKeySelective(record);
			}else{
				result.setSuccess(false);
				result.setMessage("评论失败");
			}
		}
		return result;
	}
	
	/**
	 * 资源评论列表
	 */
	@RequestMapping("commentList")
	@ResponseBody
	public PageData<ResourceCommentModel> commentList(ResourceCommentModel comment,HttpServletRequest request){
		return this.resourceCommentService.commentList(comment);
	}
	
}
